using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.productpurchaseprices;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.productpurchaseprices
{
    /// <summary>
    /// 删除商品采购价格命令处理器
    /// </summary>
    public class DeleteProductPurchasePriceCommandHandler : IRequestHandler<DeleteProductPurchasePriceCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<ProductPurchasePrice> _productPurchasePriceRepository;
        private readonly ILogger<DeleteProductPurchasePriceCommandHandler> _logger;

        public DeleteProductPurchasePriceCommandHandler(
            IBaseRepository<ProductPurchasePrice> productPurchasePriceRepository,
            ILogger<DeleteProductPurchasePriceCommandHandler> logger)
        {
            _productPurchasePriceRepository = productPurchasePriceRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除商品采购价格命令
        /// </summary>
        /// <param name="request">删除商品采购价格命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(DeleteProductPurchasePriceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证商品采购价格是否存在
                var existingPrice = await _productPurchasePriceRepository.GetAll()
                    .FirstOrDefaultAsync(p => p.Id == request.Id && !p.IsDeleted, cancellationToken);

                if (existingPrice == null)
                {
                    return ApiResult<bool>.Error("商品采购价格不存在");
                }

                // 执行软删除
                existingPrice.IsDeleted = true;
                existingPrice.UpdatedTime = DateTime.Now;

                // 删除商品采购价格
                var result = await _productPurchasePriceRepository.UpdateAsync(existingPrice);

                if (result>0)
                {
                    _logger.LogInformation("成功删除商品采购价格，ID: {PriceId}, 商品: {ProductName}, 规格: {Specification}", 
                        existingPrice.Id, existingPrice.ProductName, existingPrice.Specification);
                    
                    return ApiResult<bool>.Success(true, "商品采购价格删除成功");
                }
                else
                {
                    _logger.LogError("删除商品采购价格失败，ID: {PriceId}, 商品: {ProductName}, 规格: {Specification}", 
                        existingPrice.Id, existingPrice.ProductName, existingPrice.Specification);
                    
                    return ApiResult<bool>.Error("商品采购价格删除失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除商品采购价格时发生异常，ID: {PriceId}", request.Id);
                
                return ApiResult<bool>.Error("删除商品采购价格时发生异常");
            }
        }
    }
} 